<template>
    <vp-dialog :span="4" ref="editDialogRef">
        <template #title>
            <vp-label zh="新增" en="Add Abnormal List" v-if="type === 'add'" />
            <vp-label zh="修改" en="Edit Abnormal List" v-else />
        </template>
        <div v-loading="loading">
            <Material :type="type" ref="materialRef" />
        </div>
        <template #footer>
            <vp-btn-confirm @click="handleSave" />
        </template>
    </vp-dialog>
</template>
<script setup lang="ts" name="EditMaterial">
import { nextTick, ref } from 'vue';
import { ElMessage } from "element-plus";
import request from '/@/utils/request';
import Material from './material.vue';

const emits = defineEmits<{
    (e: 'formSubmited'): void
}>()

const loading = ref(false);
const saveLoading = ref(false);
const type = ref('add');

const formData = ref({
    id: '',
    zt: 10,
    yxbs: 1,
});

const editDialogRef = ref();
const materialRef = ref();

const handleOpen = (param: { type: string; id: any; }) => {
    type.value = param.type;
    editDialogRef.value.handleOpen();
    nextTick(() => {
        if (param.type === 'edit') {
            loading.value = true;
            request.get(`/basicData/material/${param.id}`).then((res) => {
                const data = { ...res.data };

                data.syjxText=data.syjx==10?"ALL":data.syjx==20?data.actypeList.join(","):'';

                materialRef.value.setData(data);
                loading.value = false;
            })
        } else {
            materialRef.value.setData({
                ...formData,
                ...param,
            });
        }
    });
}

const handleSave = () => {
    if (loading.value) {
        return;
    }
    saveLoading.value = true;
    materialRef.value.getData().then((data: any) => {

        console.log(data,"data","/basicData/material/" + type.value)

        request.post("/basicData/material/" + type.value, {
            ...data
        }).then(() => {
            ElMessage.success("操作成功/Operation Succeeded");
            emits("formSubmited");
            editDialogRef.value.handleClose();
        }).finally(() => {
            saveLoading.value = false;
        })
    }).catch(() => { saveLoading.value = false; });
}

defineExpose({
    handleOpen
})
</script>